package com.linglan.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.json.JSONUtil;
import com.linglan.common.api.R;
import com.linglan.common.api.ResultCode;
import com.linglan.common.utils.I18nMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.nio.file.AccessDeniedException;
import java.util.List;

/**
 * @author jp
 * @date 2021-08-24
 */
@Slf4j
@RestController
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * ServiceException 业务执行异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleGlobalServiceException(Exception e, HttpServletRequest request) {
        log.error("RequestURI ={} ParameterMap ={} 全局异常信息 ex={}", request.getRequestURI(), JSONUtil.toJsonStr(request.getParameterMap()), e.getMessage(), e);
        return R.failed(e.getMessage());
    }

    /**
     * 未授权代码
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public R handleNotLoginException(NotLoginException e, HttpServletRequest request) {
        //未授权
        String message = "";
        if (e.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未提供token";
        } else if (e.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token无效";
        } else if (e.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token已过期";
        } else if (e.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token已被顶下线";
        } else if (e.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token已被踢下线";
        } else {
            message = "当前会话未登录";
        }
        log.error("无效的token RequestURI ={} ParameterMap ={}  method={} 全局异常信息 ex={}",
                request.getRequestURI(), JSONUtil.toJsonStr(request.getParameterMap()), request.getMethod(),e.getMessage());
        return R.failed(null, I18nMessageUtil.get(ResultCode.TOKEN_INVALID.getMessageKey()), ResultCode.TOKEN_INVALID.getCode());
    }


    /**
     * AccessDeniedException
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public R handleAccessDeniedException(AccessDeniedException e) {
        log.error("拒绝授权异常信息 ex={}", e.getMessage());
        return R.failed("请求无效");
    }

    /**
     * validation Exception
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleBodyValidException(MethodArgumentNotValidException exception) {
        List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
        log.warn("参数绑定异常 ex = {} {}", fieldErrors.get(0).getField(), fieldErrors.get(0).getDefaultMessage());
        return R.failed(fieldErrors.get(0).getDefaultMessage());
    }

    /**
     * MissingServletRequestParameterException Exception
     * 单独访问根目录
     *
     * @param exception
     * @return R
     */
    @ExceptionHandler({MissingServletRequestParameterException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public R handleNoParamException(MissingServletRequestParameterException exception, HttpServletRequest request) {
        log.error("请求无效 RequestURI ={} ParameterMap ={} ex={}",
                request.getRequestURI(), JSONUtil.toJsonStr(request.getParameterMap()), exception.getMessage());
        return R.failed("请求无效");
    }

    /**
     * ServiceException 业务执行异常.
     *
     * @param e the e
     * @return R
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleGlobalException(Exception e, HttpServletRequest request) {
        log.error("RequestURI ={} ParameterMap ={}  全局异常信息 ex={}",
                request.getRequestURI(), JSONUtil.toJsonStr(request.getParameterMap()), e.getMessage(), e);
        return R.failed(I18nMessageUtil.get(ResultCode.OPERATE_FAILED.getMessageKey()));
    }
}
